package jnpf.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.base.mapper.CostExecutionMapper;
import jnpf.base.service.CostExecutionService;
import jnpf.base.service.SuperServiceImpl;
import jnpf.base.util.ExcelImporter;
import jnpf.exception.WorkFlowException;
import jnpf.onlinedev.entity.CostExecution;
import jnpf.onlinedev.entity.CostExecutionDto;
import jnpf.onlinedev.model.RequestBodyDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

@Service
public class CostExecutionServiceImpl extends SuperServiceImpl<CostExecutionMapper, CostExecution> implements CostExecutionService {
  @Autowired
  private  CostExecutionMapper costExecutionMapper;
    @Override
    public void importFile(MultipartFile file) throws IOException {



        // 创建临时文件
        Path tempFile = Files.createTempFile("uploaded-", file.getOriginalFilename());

        // 将文件传输到临时文件
        file.transferTo(tempFile.toFile());

        System.out.println("文件地址：" + tempFile.toAbsolutePath());
        List<CostExecution> costExecutions = ExcelImporter.importExcel(tempFile.toAbsolutePath().toString(), CostExecution.class);
       /* for (CostExecution costExecution:costExecutions
             ) {
            System.out.println("费用性质-分人力与非人力:"+costExecution.getFeeNature());

        }*/


        this.saveBatch(costExecutions);


    }

    @Override
    public void deleteData3() {
        // 删除所有数据
        this.getBaseMapper().delete(new UpdateWrapper<>());
    }

    @Override
    public String CreateExcel(String filename, HttpServletResponse response) {

        Long count = this.getBaseMapper().selectCount(new UpdateWrapper<>());
        //  每页导出10万条
        int pageSize=50000;
        String th="/www/wwwroot/jnpf-resources/DocumentFile/${file_name}.xlsx";
        String filePath = th.replace("${file_name}", filename);
        ExcelWriter excelWriter = EasyExcel.write(filePath, CostExecutionDto.class)
                .build();


        for (int i=0; i<(count/pageSize)+1;i++)
        {

            Page<CostExecution> costExecutionPage = this.getBaseMapper().selectPage(new Page<>(i + 1, pageSize), null);
            List<CostExecution> records = costExecutionPage.getRecords();



            System.out.println("开始复制："+System.currentTimeMillis());
            List<CostExecutionDto> dtos = BeanUtil.copyToList(records, CostExecutionDto.class);
            System.out.println("结束复制："+System.currentTimeMillis());
            WriteSheet writeSheet = EasyExcel.writerSheet(i,+(i+1)+"").head(CostExecutionDto.class).build();
            excelWriter.write(dtos,writeSheet);
        }
        excelWriter.finish();

        return filePath;
    }

    @Override
    public void write(RequestBodyDto requestBodyDto) throws WorkFlowException {
        //  找到表的数据
        QueryWrapper<CostExecution> queryWrapper = new QueryWrapper<>();

        String old_seq = requestBodyDto.getOld_seq();
        String cleanSeq = old_seq.replace("[", "").replace("]","");

        // 按逗号分割字符串
        String[] items = cleanSeq.split(",");
        for (String  id:items
             ) {
            queryWrapper.clear();
            queryWrapper.lambda().eq(CostExecution::getId,id );

            //  旧数据
            CostExecution one = this.getOne(queryWrapper);

            if(one!=null){
                //  对数据进行更新
                one.setF_status("否");
                this.updateById(one);
            }else {
                log.error("id为[ " + requestBodyDto.getOld_seq() + " ]对用的表mt615546653398534597的数据不存在!");
                throw new WorkFlowException("id为[ " + requestBodyDto.getOld_seq() + " ]对用的表mt615546653398534597的数据不存在!");

            }

            CostExecution newCostExecution  = new  CostExecution();
            Map map = costExecutionMapper.queryBySeq(id);
            if (map != null) {





                BeanUtil.copyProperties(one, newCostExecution, "id");
                newCostExecution.setF_status("是");
                newCostExecution.setSeq(map.get("changed_seq").toString());
                if (map.get("changed_amount") != null) {
                    newCostExecution.setManagementReportAfterAdjustmentAmount(new BigDecimal(map.get("changed_amount").toString()));
                }

                if (map.get("changed_cost_center_code") != null) {
                    newCostExecution.setFinalTransposeAccountableCostCenter(map.get("changed_cost_center_code").toString());
                }

                if (map.get("changed_cost_center_name") != null) {
                    newCostExecution.setFinalTransposeAccountableCostCenterDesc(map.get("changed_cost_center_name").toString());
                }
                if (map.get("changed_department_1") != null) {
                    newCostExecution.setBudgetDept1(map.get("changed_department_1").toString());
                }
                if (map.get("changed_department_2") != null) {
                    newCostExecution.setBudgetDept2(map.get("changed_department_2").toString());
                }

                if (map.get("changed_department_3") != null) {
                    newCostExecution.setBudgetDept3(map.get("changed_department_3").toString());
                }
                if (map.get("changed_department_4") != null) {
                    newCostExecution.setBudgetDept4(map.get("changed_department_4").toString());
                }
                if (map.get("changed_final_cost_center") != null) {
                    newCostExecution.setFinalCostCenter(map.get("changed_final_cost_center").toString());
                }
                if (map.get("changed_value_chain") != null) {
                    newCostExecution.setGetValueChain(map.get("changed_value_chain").toString());
                }
                if (map.get("changed_small_fee_attr") != null) {
                    newCostExecution.setGetExpenseAttribute(map.get("changed_small_fee_attr").toString());
                }

                if (map.get("changed_small_fee_attr_second") != null) {
                    newCostExecution.setExpenseAttributeSecond(map.get("changed_small_fee_attr_second").toString());
                }

                if (map.get("changed_large_fee_attr") != null) {
                    newCostExecution.setLargeExpenseAttribute(map.get("changed_large_fee_attr").toString());
                }
                if (map.get("changed_fee_nature") != null) {
                    newCostExecution.setFeeNature(map.get("changed_fee_nature").toString());
                }


                if (map.get("changed_large_fee_type") != null) {
                    newCostExecution.setExpenseCategories(map.get("changed_large_fee_type").toString());
                }
                if (map.get("change_small_fee_type") != null) {
                    newCostExecution.setGetSmallExpenseCategories(map.get("change_small_fee_type").toString());
                }

                if (map.get("changed_account_code") != null) {
                    newCostExecution.setGetGlAccounts(map.get("changed_account_code").toString());
                }


                if (map.get("changed_account_name") != null) {
                    newCostExecution.setGet_gl_accounts_desc(map.get("changed_account_name").toString());
                }

                if (map.get("changed_large_account_class") != null) {
                    newCostExecution.setExpense_classification(map.get("changed_large_account_class").toString());
                }
                this.save(newCostExecution);

            }



        }






    }
}
